package com.huaru.message.utile;

import com.huaru.message.Vo.CourseVO;
import com.huaru.message.Vo.UsageRateVO;
import oshi.SystemInfo;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;
import sun.awt.SunToolkit;

import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

public class CourseUtils {

    public static void main(String[] args) {
//        try {
//            UsageRateVO courseInfo = getCourseInfo(2780);
//            System.out.println(courseInfo.getCpu());
//            System.out.println(courseInfo.getMemory());
//            System.out.println(courseInfo.getBytesRead());
//            System.out.println(courseInfo.getBytesWritten());
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//
//        List<CourseVO> courseList = getCourseList();
//        for (CourseVO courseVO : courseList) {
//            System.out.println(courseVO.getCourseName());
//            System.out.println(courseVO.getCourseId());
//        }

        String command = "taskkill /F /PID " + 5676;
        Process exec = null;
        try {
            exec = Runtime.getRuntime().exec(command);
            System.out.println(command);
            System.out.println(exec.waitFor());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 根据pid 杀死进程
     * @param pid
     */
    public static void kilkCourseByPid(Integer pid){
        try {
            String command = "taskkill /F /PID " + pid;
            Process exec = Runtime.getRuntime().exec(command);
            System.out.println(command);
            System.out.println(exec.waitFor());
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 获取所有进程列表
     * @return
     */
    public static List<CourseVO> getCourseList() {
        /*
         * 下面先是获取进程列表
         */
        Runtime runtime = Runtime.getRuntime();
        List tasklist = new ArrayList();
        try {
            Process process = runtime.exec("tasklist");
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), "gbk"));
            String s = "";
            while ((s = br.readLine()) != null) {
                if ("".equals(s)) {
                    continue;
                }
                tasklist.add(s + " ");
            }
            // 获取每列最长的长度
            String maxRow = tasklist.get(1) + "";
            String[] maxCol = maxRow.split(" ");
            // 定义映像名称数组
            String[] taskName = new String[tasklist.size()];
            // 定义 PID数组
            String[] taskPid = new String[tasklist.size()];
            // 会话名数组
            String[] taskSessionName = new String[tasklist.size()];
            // 会话#数组
            String[] taskSession = new String[tasklist.size()];
            // 内存使用 数组
            String[] taskNec = new String[tasklist.size()];
            for (int i = 0; i < tasklist.size(); i++) {
                String data = tasklist.get(i) + "";
                for (int j = 0; j < maxCol.length; j++) {
                    switch (j) {
                        case 0:
                            taskName[i] = data.substring(0, maxCol[j].length() + 1);
                            data = data.substring(maxCol[j].length() + 1);
                            break;
                        case 1:
                            taskPid[i] = data.substring(0, maxCol[j].length() + 1);
                            data = data.substring(maxCol[j].length() + 1);
                            break;
                        case 2:
                            taskSessionName[i] = data.substring(0, maxCol[j].length() + 1);
                            data = data.substring(maxCol[j].length() + 1);
                            break;
                        case 3:
                            taskSession[i] = data.substring(0, maxCol[j].length() + 1);
                            data = data.substring(maxCol[j].length() + 1);
                            break;
                        case 4:
                            taskNec[i] = data;
                            break;
                    }
                }
            }

            List<CourseVO> list = new ArrayList<>();
            for (int i = 0; i < taskNec.length; i++) {
                if (i == 0 || i == 1) {
                    continue;
                }
                CourseVO courseVO = new CourseVO();
                courseVO.setCourseName(taskName[i].replaceAll(" ",""));
                courseVO.setCourseId(taskPid[i].replaceAll(" ",""));
                list.add(courseVO);
            }
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 根据某个进程ID 来获取进程详细信息
     * @param pid
     * @return
     * @throws Exception
     */
    public static UsageRateVO getCourseInfo(Integer pid) {
        SystemInfo systemInfo = new SystemInfo();
        OperatingSystem os = systemInfo.getOperatingSystem();
        OSProcess process = os.getProcess(pid);
        long curBytesWritten = process.getBytesWritten();
        long curBytesRead = process.getBytesRead();
        UsageRateVO usageRateVO = new UsageRateVO();
        usageRateVO.setMemory( new BigDecimal((process.getResidentSetSize()/(1024.0*1024.0))).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        try {
            usageRateVO.setCpu(new BigDecimal((getProcessCpuLoad()/(1024.0*1024.0))).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        } catch (Exception e) {
            e.printStackTrace();
        }
        usageRateVO.setBytesWritten(new BigDecimal((curBytesWritten/(1024.0*1024.0))).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        usageRateVO.setBytesRead(new BigDecimal((curBytesRead/(1024.0*1024.0))).setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue());
        return usageRateVO;

    }

    /**
     * 获取当前进程的CPU利用率
     * @return
     * @throws Exception
     */
    public static double getProcessCpuLoad() throws Exception {

        MBeanServer mbs    = ManagementFactory.getPlatformMBeanServer();
        ObjectName name    = ObjectName.getInstance("java.lang:type=OperatingSystem");
        AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" });

        if (list.isEmpty()) {
            return Double.NaN;
        }

        Attribute att = (Attribute)list.get(0);
        Double value  = (Double)att.getValue();

        // usually takes a couple of seconds before we get real values
        if (value == -1.0) {
            return Double.NaN;
        }
        // returns a percentage value with 1 decimal point precision
        return ((int)(value * 1000) / 10.0);
    }
}
